<?php
/**
 * 预览和保存page
 *
 */
require_once 'lib/CException.php';
require_once 'services/IdCountService.php';
require_once 'services/PageService.php';

class PreviewController extends Controller{

	public function show(){
		if( !parent::getRequest()->isPost() ){
			throw new CException('操作错误', 500);
		}
		$url = parent::getRequest()->getParam('url');
		$path = parse_url($url);
		if( !isset( $path['path'] ) ){
				return false;
		}
		if( !isset($path['scheme'])){
			$url = "http://".$url;
		}

		$contents = file_get_contents($url, false, null, -1);

		$dom = new simple_html_dom(null, true, true, DEFAULT_TARGET_CHARSET, DEFAULT_BR_TEXT);

		if (empty($contents)){
			return false;
		}

		$dom->load($contents,true, true);
		$charset = $dom->find('meta[charset]', 0 )->charset;
		if(empty($charset)){
			$charset = $dom->find('meta[http-equiv*=content-type]', 0)->content;
			$charset = str_replace('=', '', strstr($charset, '='));
		}
		$title = $dom->find('title', 0)->plaintext;
		$description = $dom->find('meta[name=description]', 0)->content;
		if( "utf-8" != strtolower( $charset )){
			$title = mb_convert_encoding($title, "UTF-8", $charset);   
			$description = mb_convert_encoding($description, "UTF-8", $charset);   
		}
		$img = $dom->find('img', 0)->src;
		/*
		foreach($dom->find('img') as $img){
				//echo $img->src."<br />";
		}
		*/
		$dom->clear();

		include parent::getRender();	
	}

	/**
	 * 发表
	 */
	public function post(){
		$user		=	 parent::getUser();
		if( empty( $user ) ){
			echo 'goto login page!';
			exit;
		}

		$user_id     = $user['uid'];
		$options = array();

		$idCountService = new IDCountService();
		$options['page_id'] = $idCountService->generateId();

		/* 连接入库展现需要转义 */
		$options['title']			 	= parent::getRequest()->getParam('title');
		$options['description'] = parent::getRequest()->getParam('description');
		$options['url']         = parent::getRequest()->getParam('url');
		$options['img']				 	= parent::getRequest()->getParam('img');
		$options['ip'] 					= parent::getRequest()->getIp();
		$options['status']  		= 1;
		$options['load_time']  	= time();
		/* 这里需要处理图片、视频、歌曲等，图片需要上传到存储服务器*/
		$pageService = new PageService();			
		$ret = $pageService->addUserPage($user_id, $options );
		echo $options['page_id'].'------'.$ret;
	}

}

